
function mathSum(arr, n, sum) {
    let result = [];
    let temp = [];
    let dep = 0;

    function dfs(temp,dep) {

        if (temp.length == n) {
            let count = temp.reduce((pre, next) => pre + next)
            if (count == sum) {
                result.push(temp)
                // 如果只要返回一个
                // return temp
                // ----------
            }
            return
        }
        for (let i = 0; i < arr.length; i++) {
            let current = arr.shift()
            temp.push(current)
            dfs(temp.slice(),dep)
            // 如果只要返回一个
            // if (result) return result
            // ---------
            temp.pop()
            arr.push(current)
        }
    }
    // return dfs(temp, dep)
    dfs(temp, dep)
    return result

}

const arr = [1, 5, 6, 2, 4, 3]
console.log(mathSum(arr, 3, 10))
console.log("====================")


/**
* 
* 解题思路：从array中取出n个数全排列，在取的同时判断是否符合条件，为了不影响后续排列，每次递归完成，将当前的数组添加到正在排序的array中
* 时间复杂度O(n)
* 空间复杂度O(n)
* @param {Array} array 需要判断的数组
* @param {number} n 取出n个数
* @param {number} sum 和为sum的值
* @param {array} temp 输出和为sum的数组 
*/

function getAllCombin(array, n, sum, temp) {
    if (temp.length === n) {
        if (temp.reduce((t, c) => t + c) === sum) {
            return temp;
        }
        return false;
    }
    for (let i = 0; i < array.length; i++) {
        const current = array.shift();
        temp.push(current);
        const result = getAllCombin(array, n, sum, temp);
        if (result) {
            return result;
        }
        temp.pop();
        array.push(current);
    }
}

console.log(getAllCombin(arr, 3, 10, []));
console.log(getAllCombin([2,11,20,160,3,1,77],3,100,[]));
console.log(getAllCombin([-1,0,1,2,-1,-4],3,0,[])) // 只能找出一个
console.log(getAllCombin([-1,0,1,2,-1,-4],3,0,[]))